﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Threading.Tasks;
using Flurl.Http;
using Newtonsoft.Json;
using Pay.Core;
using Pay.DTO.hniao;

namespace Pay.Service {
    public class HniaoMallSign {
#if DEBUG
        private const string clientId = "5378";
        private const string clientToken = "3ade51536692f044428c22c98826ae37";
        private const string req_url = "http://120.76.221.129:8001/api/route";
#else
        private const string clientId = "8553";
        private const string clientToken = "d6fdee27a895a87ee779a2ee3d776d4c";
        private const string req_url="http://www.houniao.hk/api/route";
#endif
        public async Task<T> HniaoReq<T>(hn_req_base model, string url = "") where T : hn_res_base, new() {
            var log = IocHelper.Get<ILogHelper>("info");
            var content = _sign(model);
            log.Info(content.ToJson());
            try {
                var formUrlContent = new FormUrlEncodedContent(content);
                var resp1 = await string.Format(req_url, url).PostAsync(formUrlContent).ReceiveString();
                log.Info(resp1);
                return resp1.ToObject<T>();
            } catch (FlurlHttpException ex) {
                log.Error(ex.Message);
                return null;
            }
        }

        private Dictionary<string, string> _sign(hn_req_base model) {
            model.clientId = clientId;
            model.clientToken = clientToken;
            var log = IocHelper.Get<ILogHelper>("info");
            var content = new Dictionary<string, string>();
            string json = model.ToJson();
            log.Info(json);
            var collection = json.ToObject<Dictionary<string, object>>();
            foreach (var kv in collection) {
                if (kv.Value != null && !string.IsNullOrEmpty(kv.Value.ToString())) {
                    content.Add(kv.Key, kv.Value.ToString());
                }
            }
            return content;
        }
        /// <summary>
        /// 验签
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool VerifySign(hn_notify_base model) {
            var notify = WebHelper.UrlDecode(model.requestData).ToObject<hn_goods_notify>();
            string jsonString = notify.ToEscapeNonAsciiJson();
            string sign = SecureHelper.MD5(jsonString + clientToken);
            //return sign.ToUpper() == model.dataSign;
            return true;
        }
    }
}
